package com.ht.common.core.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

import com.ht.common.core.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据权限以关区代码隔离
 *
 * @author Administrator
 */
public class DataScopeUtils {
    protected final static Logger logger = LoggerFactory.getLogger(DataScopeUtils.class);

    public static void setDataScope(Object obj, String customsData) {
        try {
            String searchCusomsCode = checkSearchCusCode(obj);
            if (StringUtils.isNotBlank(searchCusomsCode)) {
                customsData = searchCusomsCode;
            }

            if (StringUtils.isNotBlank(customsData)) {
                if (customsData.equals("ALL") || Constants.KMHG.equals(searchCusomsCode)|| customsData.contains(Constants.KMHG)) {
                    return;
                }
                List<String> cusList = StringUtils.stringToList(customsData, ",");
                if (StringUtils.isNotEmpty(cusList)) {
                    String cussql = cusList.stream().collect(Collectors.joining("','"));
                    cussql = "'" + cussql + "'";
                    Class superClass = obj.getClass().getSuperclass();
                    Method method = superClass.getDeclaredMethod("setCustomsData", String.class);
                    method.invoke(obj, cussql);
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    private static String checkSearchCusCode(Object obj) {
        String searchCusomsCode = null;
        Class curClass = obj.getClass();
        Method[] methods = curClass.getDeclaredMethods();
        for (Method method : methods) {
            try {
                String methodName = method.getName();
                if (methodName.equals("getCustomCode") || methodName.equals("getCustomsNo")|| methodName.equals("getCustomsCode") || methodName.equals("getCustomNo") || methodName.equals("getCusCode")) {
                    String cusCode = (String) method.invoke(obj);
                    if (StringUtils.isNotBlank(cusCode)) {
                        searchCusomsCode = cusCode;
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return searchCusomsCode;
    }

}
